#!/bin/bash
shopt -s extglob

if [ -n "$(git status --porcelain --untracked-files=no)" ]; then
    DIRTY="-dirty"
fi

COMMIT=$(git rev-parse --short HEAD)
COMMIT_DATE=$(git --no-pager log -1 --format='%ct')
COMMIT_BRANCH=$(git rev-parse --abbrev-ref HEAD | sed -E 's/[^a-zA-Z0-9]+/-/g')
GIT_TAG=${DRONE_TAG:-$(git tag -l --contains HEAD | head -n 1)}
LAST_TAG=${GIT_TAG:-'v0.0.0'}

if [[ -z "$DIRTY" && -n "$GIT_TAG" ]]; then
    VERSION=$GIT_TAG
else
    VERSION="${COMMIT}${DIRTY}"
fi

if [ -z "$DRONE_TAG" ] && [ -n "$DRONE_COMMIT" ] && [ -n "$DRONE_BRANCH" ]; then
    APP_VERSION=${DRONE_BRANCH/release\//}-${DRONE_COMMIT}-head
else
    APP_VERSION=$VERSION
fi

# Chart tag.
if [[ -z "${DIRTY}" && -n "${GIT_TAG}" ]]; then
    CHART_VERSION="${GIT_TAG}"
elif [[ "$DIRTY" ]]; then
    CHART_VERSION="${LAST_TAG}${DIRTY}.commit-${COMMIT}"
else
    CHART_VERSION="${LAST_TAG}-${COMMIT_DATE}.commit-${COMMIT}.${COMMIT_BRANCH}"
fi

# Drop the v prefix for Chart Version to follow existing pattern.
CHART_VERSION="$(echo ${CHART_VERSION} | sed -E 's/^v//' | sed -e 's/^\(.\{55\}\).*/\1/')"

# Chart Repo - Target Repo for releases.
case $CHART_VERSION in
    *-alpha*) # All alpha tags
        CHART_REPO="alpha" ;;
    *-rc*) # All rc tags
        CHART_REPO="latest" ;;
    +([0-9]).+([0-9]).+([0-9])) # All release tags
        CHART_REPO="latest" ;;
    *) # Anything else - Future use
        CHART_REPO="dev" ;;
esac

if [ -z "$ARCH" ]; then
    ARCH=amd64
fi

SUFFIX=""
[ "${ARCH}" != "amd64" ] && SUFFIX="_${ARCH}"

TAG=${TAG:-${VERSION}${SUFFIX}}
REPO=${REPO:-rancher}

if echo $TAG | grep -q dirty; then
    TAG=dev
fi

if [ -n "$DRONE_TAG" ]; then
    TAG=$DRONE_TAG
fi

AGENT_TAG="$TAG"
if [ "$AGENT_TAG" = dev ]; then
    AGENT_TAG="master-head"
fi

echo "ARCH: $ARCH"
echo "CHART_REPO: $CHART_REPO"
echo "CHART_VERSION: $CHART_VERSION"
echo "VERSION: $VERSION"
echo "APP_VERSION: $APP_VERSION"
echo "SUFFIX: $SUFFIX"
echo "REPO: $REPO"
echo "TAG: $TAG"
echo "AGENT_TAG: $AGENT_TAG"
